# -*- coding: utf-8 -*-
#
# Copyright 2017 zhangxp, st
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import socket
from logbook.handlers import Handler, StringFormatterHandlerMixin
from logbook.base import NOTSET

from rqalpha.environment import Environment


class LogHandler(Handler, StringFormatterHandlerMixin):
    def __init__(self, send_log_handler, level=NOTSET, format_string=None, filter=None, bubble=False):
        Handler.__init__(self, level, filter, bubble)
        StringFormatterHandlerMixin.__init__(self, format_string)
        self.send_log_handler = send_log_handler

    def _write(self, level_name, item):
        dt = Environment.get_instance().calendar_dt
        self.send_log_handler(dt, item, level_name)

    def emit(self, record):
        msg = self.format(record)
        try:
            self._write(record.level_name, msg)
        finally:
            pass


if __name__ == '__main__':
    #
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(('', 6000))
    print("UDP bound on port 6000...")

    while True:
        data, addr = s.recvfrom(2048)
        try:
            data_str = data.decode()
        except UnicodeDecodeError as u:
            print(u)
            data_str = data.decode(encoding='gb18030')
        if data_str.startswith("WARN"):
            print("Receive %s from %s" % (data_str[4:], addr))
        elif data_str.startswith("ERROR"):
            print("Receive %s from %s" % (data_str[5:], addr))